<?php

/**
 * 
 * 
 *
 */
class Quad_Date_Period implements Iterator {
 
	const EXCLUDE_START_DATE = 1;
	protected $_start;
	protected $_interval;
	protected $_end;
	protected $_excludeStart = false;
	protected $_current;
	protected $_position = 0;
	
	// PHP native spec: http://www.php.net/manual/en/dateperiod.construct.php
	// DatePeriod::__construct ( string $isostr [, int $options ] )	
	// DatePeriod::__construct ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
	// DatePeriod::__construct  ( DateTime $start  , DateInterval $interval  , int $recurrences  [, int $options  ] )
  public function __construct() {
  	$start = $interval = $recurrences = $end = null;
  	
  	$a = func_get_args();
  	if (is_string($a[0])) {
  		// not yet supported
  		list ($isostr, $options) = $a;
  		// TODO: convert to start / recurrences / end
  	}
  	elseif ($a[0] instanceof Quad_Date && $a[2] instanceof Quad_Date) {
  		list ($start, $interval, $end, $options) = $a;
  	}
  	elseif ($a[0] instanceof Quad_Date && is_numeric($a[2])) {
  		list ($start, $interval, $recurrences, $options) = $a;
  	}
  	$this->_start = $start;
  	$this->_interval = Quad_Date_StrtotimeInterval::create($interval);
  	$this->_end = $end;
  	$this->_recurrences = $recurrences; // TODO: check for negative
  	
  	if (($options & self::EXCLUDE_START_DATE) == self::EXCLUDE_START_DATE) {
  		$this->_excludeStart = true;
  	}
		$this->rewind();
  }

  // Iterator Interface Functions
  public function current() {
    return $this->_current;
  }
 
  public function key() {
    return $this->_position;
  }
 
  public function next() {
  	$this->_current = $this->_start->add($interval->spec);
  	$this->_position++;
  	if (!$this->valid()) {
//			$this->_current = false;
//  		$this->_position = 0;  		
  		return false;
  	}
    return $this->_current;
  }
 
  public function rewind() {
  	$this->_position = 0;
    $this->_current = $this->_start;
  	if ($this->_excludeStart) {
  		$this->_current = $this->next();
  		$this->_position = 0;
  	}
    if ($this->_current > $this->_end) {
    	// i.e. "empty"
  		return false;
  	}
    return $this->_current;
  }
 
  public function valid() {
  	if (
  		($this->_end && $this->_current > $this->_end) ||
  		($this->_position > $this->_recurrences)
  	) {
  		return false;
  	}
    return true;
  }
 
  public function getIterator() {
    return $this;
  }
    
}